﻿using Doolin.MongoRepository.Commons;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;

namespace Doolin.MongoRepository
{
  public class MongoDbContext : IMongoDbContext
  {

    private readonly IMongoClient _client;
    private readonly IMongoDatabase _database;

    public MongoDbContext(string username, string password, string dbauth, string dbname, string host, int port)
    {
      MongoInternalIdentity internalIdentity = new MongoInternalIdentity(dbname, username);
      PasswordEvidence passwordEvidence = new PasswordEvidence(password);
      MongoCredential mongoCredential = new MongoCredential(dbauth, internalIdentity, passwordEvidence);
      MongoClientSettings settings = new MongoClientSettings();
      settings.Credential = mongoCredential;
      MongoServerAddress address = new MongoServerAddress(host, port);
      settings.Server = address;
      _client = new MongoClient(settings);
      _database = _client.GetDatabase(dbname);
    }
    public MongoDbContext(DBSetting setting)
    {
      MongoInternalIdentity internalIdentity = new MongoInternalIdentity(setting.DBName, setting.Username) ;
      PasswordEvidence passwordEvidence = new PasswordEvidence(setting.Password);
      MongoCredential mongoCredential = new MongoCredential(setting.DBAuth, internalIdentity, passwordEvidence);
      MongoClientSettings settings = new MongoClientSettings();
      settings.Credential = mongoCredential;
      MongoServerAddress address = new MongoServerAddress(setting.Host, setting.Port);
      settings.Server = address;
      _client = new MongoClient(settings);
      _database = _client.GetDatabase(setting.DBName);

    }
    public MongoDbContext(string connectionString, string dbName)
    {
      _client = new MongoClient(connectionString);
      _database = _client.GetDatabase(dbName);
    }

    public Task AddCommand(Func<Task> func)
    {
      throw new NotImplementedException();
    }

    public void Dispose()
    {
      GC.SuppressFinalize(this);
    }

    public IMongoCollection<BsonDocument> GetBsonMongoCollection(string collectionName)
    {
      return _database.GetCollection<BsonDocument>(collectionName);
    }
    public IMongoCollection<TEntity> GetCollection<TEntity>()
    {
      return _database.GetCollection<TEntity>(typeof(TEntity).Name);
    }
    public IMongoCollection<TEntity> GetCollection<TEntity>(string collectionName)
    {
      return _database.GetCollection<TEntity>(collectionName);
    }

    public int SaveChanges()
    {
      return 0;
    }
  }
}